#include "fileTransfer.h"

int uploadHandle(int sockfd)
{
    train_t train;
    char filename[4096];
    int fd;

    // 接收文件名
    recv(sockfd, &train.length, sizeof(train.length), MSG_WAITALL);
    recv(sockfd, train.data, train.length, MSG_WAITALL);
    memcpy(filename, train.data, train.length);
    filename[train.length] = '\0'; // 确保字符串终止

    // 创建文件（覆盖旧文件）
    // 如果文件已经存在，判断是否需要断点续传
    fd = open(filename, O_RDWR | O_CREAT | O_TRUNC, 0666);


    // 循环接收文件内容
    while (1)
    {
        recv(sockfd, &train.length, sizeof(train.length), MSG_WAITALL);
        printf("%d\n", train.length);
        if (train.length == 0)
        {
            break;
        }
        recv(sockfd, train.data, train.length, MSG_WAITALL);
        write(fd, train.data, train.length);
    }

    close(fd);
    return 0;
}
